<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of UserController
 *
 * @author zelic
 */
class UserController extends Controller {

    public function index() {
        $db = new Db();
        $statement = $db->getStatement();
        $statement->selectStatement("user");
        $tree = new TemplateTree();
        $result = $db->query($statement, Db::FETCH_ASSOC);
        $index = 1;
        foreach ($result as $row) {
            $loop = $tree->addSection("loop");
            $loop->setVariable("no", "" . $index);
            $loop->setVariable("username", $row["username"]);
            $loop->setVariable("id", $row["id"]);
            $index++;
        }
        $this->response->write($this->template->render($tree));
    }

    public function add() {
        if ($this->request->isPost()) {
            $db = new Db();
            $statement = $db->getStatement();
            $statement->insertStatement("user", array("username" => $this->data["username"]));
            $result = $db->execute($statement);
            if (!$result) {
                Logger::error("Cannot insert new user");
            }
            $this->response->redirect("/user/index");
        } else {
            $tree = new TemplateTree();
            $this->response->write($this->template->render($tree));
        }
    }

    public function edit() {
        if ($this->request->isPost()) {
            $db = new Db();
            $statement = $db->getStatement();
            $statement->updateStatement("user", array("id" => $this->data["id"]), array("username" => $this->data["username"]));
            $result = $db->execute($statement);
            if (!$result) {
                Logger::error("Cannot update user " . $this->data["id"]);
            }
            $this->response->redirect("/user/index");
        } else {
            $id = $this->data["id"];
            $tree = new TemplateTree();
            $tree->setVariable("id", $id);
            $db = new Db();
            $statement = $db->getStatement();
            $statement->selectStatement("user", array("id" => $id));
            
            //Using fetch here to get one per one row of the result
            $result = $db->query($statement, Db::FETCH_ASSOC)->fetch();
            
            if ($result != null) {
                $tree->setVariable("username", $result["username"]);
                $this->response->write($this->template->render($tree));
            } else {
                $this->response->redirect("/user/index");
            }
        }
    }
    
    public function delete(){
        $id = $this->data["id"];
        $db = new Db();
        $statement = $db->getStatement();
        $statement->deleteStatement("user", array("id" => $id));
        $result = $db->execute($statement);
        if ($result) {
            $this->response->redirect("/user/index");
        }
    }

}

?>
